package com.framework.tomcat.ex03.pyrmont.processor;

import com.framework.tomcat.ex03.pyrmont.HttpRequest;
import com.framework.tomcat.ex03.pyrmont.HttpResponse;
import com.framework.tomcat.ex03.pyrmont.connector.http.HttpConnector;
import com.framework.tomcat.ex03.pyrmont.connector.http.HttpHeader;
import com.framework.tomcat.ex03.pyrmont.connector.http.SocketInputStream;
import org.apache.catalina.util.StringManager;

import javax.servlet.ServletException;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;

/**
 * @author LIN
 * @date 2022-06-06 21:17
 */
public class HttpProcessor {
    private HttpRequest request;
    private HttpResponse response;
    private StringManager sm;

    private HttpRequestLine requestLine = new HttpRequestLine();

    public HttpProcessor(HttpConnector httpConnector) {

    }

    public void process(Socket socket) {
        SocketInputStream input = null;
        OutputStream output = null;
        try{
            input = new SocketInputStream(socket.getInputStream(), 2048);
            output = socket.getOutputStream();

            // create HttpRequest object and parse
            request = new HttpRequest(input);
            // create HttpResponse object
            response = new HttpResponse(output);
            response.setRequest(request);
            
            response.setHeader("Server","Pyrmont Servlet Container");
            parseRequest(input, output);
            parseHeaders(input);
            // check if this is a request for a servlet or a static resource
            // a request for a servlet begins with "/servlet/"
            if(request.getRequestURI().startsWith("/servlet/")){

            }else{

            }

            // Close the socket
            socket.close();
            // no shutdown for this application


        }catch(Exception e){
            e.printStackTrace();
        }

    }

    private void parseHeaders(SocketInputStream input) {
        input.readHeader(new HttpHeader());

    }

    private void parseRequest(SocketInputStream input, OutputStream output) throws IOException, ServletException {
        // Parse the incoming request line
        input.readRequestLine(requestLine);
        // Validate the incoming request line

        // Parse any query parameters out of the request URI

        // Checking for an absolute URI (with the HTTP protocol)

        // Parsing out protocol and host name
        // Parse any requested session ID out of the request URI

        // Normalize URI (using String operations at the moment)

        // Set the corresponding request properties



    }

}
